import Vue from 'vue'
import Router from 'vue-router'
import Layout from '@/layout'
import store from '@/store/index.js'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false })
Vue.use(Router)

export const constantRoutes = [
    {
        path: '/login',
        component: () => import('@/views/login/index')
    },
    {
        path: '/404',
        component: () => import('@/views/error-page/404')
    },
    {
        path: '/500',
        component: () => import('@/views/error-page/500')
    },
    {
        path: '/',
        component: Layout,
        redirect: '/index',
        children: [
            {
                path: 'index',
                component: () => import('@/views/home/index.vue')
            }
        ]
    }
]

const router = new Router({
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRoutes
})
router.beforeEach((to, from, next) => {
    NProgress.start()
    if (
        constantRoutes
            .filter((v) => v.path != '/')
            .map((v) => v.path)
            .includes(to.path)
    ) {
        next()
        return
    }
    if (!store.state.user.id) {
        store
            .dispatch('user/getLoginInfo')
            .then(() => {
                next({ ...to, replace: true })
            })
            .catch((data) => {
                next('/login')
            })
    } else {
        next()
    }
})
router.afterEach((to, from) => {
    NProgress.done()
    if (to.path.includes(from.path)) {
        let opendMenus = store.state.menus.opendMenus
        let openMenu = opendMenus.find((v) => v.name == from.path)
        if (openMenu) {
            openMenu.nest = { path: to.path, query: to.query }
        }
    }
})
export default router
